package com.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.activity.adapter.CategoryAdapter;
import com.activity.adapter.ItemDragAdapter;
import com.activity.bean.CategoryBean;
import com.activity.bean.UserBean;
import com.api.param.CategoryParam;
import com.api.param.SortParam;
import com.api.param.UpdateCategoryParam;
import com.api.param.UpdateUserParam;
import com.api.param.UserParam;
import com.api.viewModel.LoginVM;
import com.api.viewModel.StoreVM;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.donkingliang.groupedadapter.adapter.GroupedRecyclerViewAdapter;
import com.donkingliang.groupedadapter.holder.BaseViewHolder;
import com.example.apple.ddhr_new.R;
import com.example.apple.ddhr_new.activity.widget.Dialog;
import com.example.apple.ddhr_new.utils.ActivityUtil;
import com.example.apple.ddhr_new.utils.StringUtil;
import com.example.apple.ddhr_new.utils.ToastUtil;
import com.example.lzbase.BaseViewModelActivity;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import event.MessageEvent;
import me.kareluo.ui.OptionMenu;
import me.kareluo.ui.OptionMenuView;
import me.kareluo.ui.PopupMenuView;

public class CategoryActivity extends BaseViewModelActivity<StoreVM> {


    @BindView(R.id.ed_text)
    EditText edText;
    @BindView(R.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.l_empty)
    LinearLayout lEmpty;

    private ArrayList<CategoryBean> arrayList;
    private CategoryAdapter categoryAdapter;
    private ItemDragAdapter itemDragAdapter;
    private boolean isedit;
    private String parentId;
    private boolean isHeader;
    private int group;
    private int child;
    private int start;
    private int end;
    @Override
    protected int titleText() {
        return R.string.zhuanji_guanli;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_category;

    }

    @Override
    protected void created(@Nullable Bundle savedInstanceState) {
        super.created(savedInstanceState);
        isedit= getIntent().getExtras().getBoolean("param",false);
        parentId= getIntent().getExtras().getString("super");
        categoryAdapter = new CategoryAdapter(this);
        recycleView.setLayoutManager(new LinearLayoutManager(this));

        if(parentId.equals("0")&&isedit){
            arrayList = new ArrayList<>();
            itemDragAdapter = new ItemDragAdapter(arrayList);

            itemDragAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    isHeader =true;
                    group =position;

                    Bundle bundle = new Bundle();
                    bundle.putString("title", "修改专辑");
                    bundle.putString("hint", "请输入专辑名称");
                    bundle.putString("content", arrayList.get(position).getWorkscategoryname());
                    bundle.putString("type", "3");
                    ActivityUtil.startActivity(CategoryActivity.this, EditActivity.class, bundle, 100);
                }
            });
            itemDragAdapter.deleteListener = new ItemDragAdapter.DeleteListener() {
                @Override
                public void itemClick(int position) {
                    isHeader =true;
                    group =position;
                    Dialog.alert(CategoryActivity.this, "确认删除此专辑内容", "本操作将同时删除专辑下的所有作品", new Dialog.OnDialogOkClickListener() {
                        @Override
                        public void onClick(Object o) {

                        }
                    }, new Dialog.OnDialogOkClickListener() {
                        @Override
                        public void onClick(Object o) {
                            UpdateCategoryParam param = new UpdateCategoryParam();
                            param.workscategoryid = arrayList.get(position).getWorkscategoryid();
                            param.parentid = arrayList.get(position).getWorkscategoryparentid();
                            addSubscription(viewModel.deleteCategory(param));
                        }
                    });

                }
            };
            ItemDragAndSwipeCallback itemDragAndSwipeCallback = new ItemDragAndSwipeCallback(itemDragAdapter);
            ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemDragAndSwipeCallback);
            itemTouchHelper.attachToRecyclerView(recycleView);

// 开启拖拽
            itemDragAdapter.enableDragItem(itemTouchHelper, R.id.r_header, true);
            itemDragAdapter.setOnItemDragListener(new OnItemDragListener() {
                @Override
                public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int i) {


                    start = i;
                }

                @Override
                public void onItemDragMoving(RecyclerView.ViewHolder viewHolder, int i, RecyclerView.ViewHolder viewHolder1, int i1) {

                }

                @Override
                public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int i) {
                    end = i;

                    if(start==end)

                        return;;

                    ArrayList<String> IDS = new ArrayList<>();
                    for (int index=0;index<arrayList.size();index++){
                        IDS.add(arrayList.get(index).getWorkscategoryid());

                    }

                    SortParam sortParam = new SortParam();
                    sortParam.workscategorylist = StringUtils.join(IDS,",");
                    addSubscription(viewModel.sortCategory(sortParam));

                }
            });
            recycleView.setAdapter(itemDragAdapter);

        }else {
            recycleView.setAdapter(categoryAdapter);

        }


        viewModel.sortCategory.observe(this,res->{
            if(res){

                EventBus.getDefault().post(new MessageEvent(MessageEvent.MESSAGE_EVENT_CATEGORY_UPDATE));

            }else {
                headerFreshing();
            }
        });

        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                headerFreshing();
            }
        });

        categoryAdapter.setOnHeaderClickListener(new GroupedRecyclerViewAdapter.OnHeaderClickListener() {
            @Override
            public void onHeaderClick(GroupedRecyclerViewAdapter adapter, BaseViewHolder holder, int groupPosition) {
                if(isedit){

                    isHeader =true;
                    group =groupPosition;

                    Bundle bundle = new Bundle();
                    bundle.putString("title", "修改专辑");
                    bundle.putString("hint", "请输入专辑名称");
                    bundle.putString("content", categoryAdapter.getData().get(groupPosition).getWorkscategoryname());
                    bundle.putString("type", "3");
                    ActivityUtil.startActivity(CategoryActivity.this, EditActivity.class, bundle, 100);
                }else {

                    Intent data = new Intent();
                    data.putExtra("id",categoryAdapter.getData().get(groupPosition).getWorkscategoryid());
                    data.putExtra("name",categoryAdapter.getData().get(groupPosition).getWorkscategoryname());
                    setResult(101,data);
                    finish();
                }
            }
        });

        categoryAdapter.setOnChildClickListener(new GroupedRecyclerViewAdapter.OnChildClickListener() {


            @Override
            public void onChildClick(GroupedRecyclerViewAdapter adapter, BaseViewHolder holder, int groupPosition, int childPosition) {

                if(isedit){
                    isHeader =false;
                    group =groupPosition;
                    child=childPosition;
                    Bundle bundle = new Bundle();
                    bundle.putString("title", "修改专辑");
                    bundle.putString("hint", "请输入专辑名称");
                    bundle.putString("content", categoryAdapter.getData().get(childPosition).getSublist().get(childPosition).getWorkscategoryname());
                    bundle.putString("type", "3");
                    ActivityUtil.startActivity(CategoryActivity.this, EditActivity.class, bundle, 100);
                }else {

                    Intent data = new Intent();
                    data.putExtra("id",categoryAdapter.getData().get(groupPosition).getSublist().get(childPosition).getWorkscategoryid());
                    data.putExtra("name",categoryAdapter.getData().get(groupPosition).getSublist().get(childPosition).getWorkscategoryname());
                    setResult(101,data);
                    finish();
                }

            }
        });
        categoryAdapter.isEdit =isedit;
        if(isedit){
            categoryAdapter.longClickListener = new CategoryAdapter.OnLongClickListener() {
                @Override
                public void OnLongHeaderClickListener(GroupedRecyclerViewAdapter adapter, BaseViewHolder baseViewHolder, int groupPosition) {
                        
                    isHeader =true;
                    group =groupPosition;
                    Dialog.alert(CategoryActivity.this, "确认删除此专辑内容", "本操作将同时删除专辑下的所有作品", new Dialog.OnDialogOkClickListener() {
                        @Override
                        public void onClick(Object o) {

                        }
                    }, new Dialog.OnDialogOkClickListener() {
                        @Override
                        public void onClick(Object o) {
                            UpdateCategoryParam param = new UpdateCategoryParam();
                            param.workscategoryid = categoryAdapter.getData().get(groupPosition).getWorkscategoryid();
                            param.parentid = categoryAdapter.getData().get(groupPosition).getWorkscategoryparentid();
                            addSubscription(viewModel.deleteCategory(param));
                        }
                    });
                }

                @Override
                public void OnLongClickListener(GroupedRecyclerViewAdapter adapter, BaseViewHolder baseViewHolder, int groupPosition, int childPosition) {

                    isHeader =false;
                    group =groupPosition;
                    child=childPosition;
                    Dialog.alert(CategoryActivity.this, "确认删除此专辑内容", "本操作将同时删除专辑下的所有作品", new Dialog.OnDialogOkClickListener() {
                        @Override
                        public void onClick(Object o) {

                        }
                    }, new Dialog.OnDialogOkClickListener() {
                        @Override
                        public void onClick(Object o) {
//                            UpdateCategoryParam param = new UpdateCategoryParam();
//                                param.workscategoryid = categoryAdapter.getData().get(groupPosition).getSublist().get(childPosition).getWorkscategoryid();
//                            param.parentid = categoryAdapter.getData().get(groupPosition).getSublist().get(childPosition).getWorkscategoryparentid();
//                                addSubscription(viewModel.deleteCategory(param));

                            UpdateCategoryParam param = new UpdateCategoryParam();
                            param.workscategoryid = categoryAdapter.getData().get(groupPosition).getWorkscategoryid();
//                            param.parentid = categoryAdapter.getData().get(groupPosition).getWorkscategoryparentid();
                            addSubscription(viewModel.deleteCategory(param));
                        }
                    });
                }
            };


        }

        headerFreshing();

        viewModel.categorys.observe(this,res->{
            if(res!=null){

                if(parentId.equals("0")&&isedit){
                    arrayList.clear();
                    arrayList.addAll(res);

                    itemDragAdapter.notifyDataSetChanged();

                }else {
                    categoryAdapter.getData().clear();
                    categoryAdapter.getData().addAll(res);

                    if(isedit){

                    }else {
                        CategoryBean categoryBean =    new CategoryBean() ;
                        categoryBean.setWorkscategoryname("无");
                        categoryBean.setWorkscategoryid("0");
                        categoryAdapter.getData().add(0,categoryBean);
                    }

                    categoryAdapter.notifyDataChanged();
                }

            }

            headerFreshEnd();
            showEmpty(res.size()==0);


        });
        viewModel.subCategorys.observe(this,res->{
            if(res!=null){
                categoryAdapter.getData().clear();
                categoryAdapter.getData().addAll(res);

                if(isedit){

                }else {
                    CategoryBean categoryBean =    new CategoryBean() ;
                    categoryBean.setWorkscategoryname("无");
                    categoryBean.setWorkscategoryid("0");
                    categoryAdapter.getData().add(0,categoryBean);
                }

                categoryAdapter.notifyDataChanged();
            }

            headerFreshEnd();
            showEmpty(categoryAdapter.getData().size()==0);


        });

        viewModel.updateCategory.observe(this,res->{
            headerFreshing();
            EventBus.getDefault().post(new MessageEvent(MessageEvent.MESSAGE_EVENT_CATEGORY_UPDATE));
        });
        viewModel.deleteCategory.observe(this,res->{
            if(parentId.equals("0")&&isedit){
                arrayList.remove(group);
                showEmpty(arrayList.size()==0);
                itemDragAdapter.notifyDataSetChanged();
            }else {
                if(isHeader){
                    categoryAdapter.getData().remove(group);
                }else {
                    categoryAdapter.getData().get(group).getSublist().remove(child);
                }

                showEmpty(categoryAdapter.getData().size()==0);
                categoryAdapter.notifyDataChanged();
            }

            EventBus.getDefault().post(new MessageEvent(MessageEvent.MESSAGE_EVENT_CATEGORY_UPDATE));

        });
        viewModel.addCategory.observe(this,res->{
            headerFreshing();
            edText.setText("");
            EventBus.getDefault().post(new MessageEvent(MessageEvent.MESSAGE_EVENT_CATEGORY_UPDATE));
        });

    }

    @OnClick(R.id.et_add)
    public void onViewClicked() {

        if(StringUtils.isEmpty(edText.getText().toString().trim()) ){

            ToastUtil.toast(this,"请输入专辑名称");
        }else
        {


            UpdateCategoryParam param = new UpdateCategoryParam();
            param.workscategoryname = edText.getText().toString().trim();
            param.parentid = parentId;
            if(param.workscategoryname.length()>4){
                ToastUtil.toast(this,"专辑名字不超过四个字");
                return;
            }
            addSubscription(viewModel.addCategory(param));


        }

    }

    protected void headerFreshing() {

        if(isedit){

            if (parentId.equals("0")) {
                addSubscription(viewModel.getCategory(new UserParam()));
            }else
            {
                CategoryParam categoryParam =new CategoryParam();
                categoryParam.categoryid = parentId;
                addSubscription(viewModel.getSubCategory(categoryParam));
            }

        }else {


            addSubscription(viewModel.getCategory(new UserParam()));
        }


    }

    protected void footerFreshing() {
        footerFreshEnd();
    }

    protected void headerFresh() {
        refreshLayout.autoRefresh();

    }

    protected void footerFresh() {
        refreshLayout.autoLoadMore();
    }

    protected void headerFreshEnd() {
        refreshLayout.finishRefresh();

    }

    protected void footerFreshEnd() {
        refreshLayout.finishLoadMore();
    }

    protected void showEmpty(boolean isEmpty) {
        if(isEmpty){

//            refreshLayout.setVisibility(View.GONE);
            lEmpty.setVisibility(View.VISIBLE);
        }else
        {
//            refreshLayout.setVisibility(View.VISIBLE);
            lEmpty.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1000 && requestCode == 100) {
            if (data.getStringExtra("type").equals("3")) {
//                data.getStringExtra("data");


                UpdateCategoryParam param = new UpdateCategoryParam();

                param.workscategoryid = categoryAdapter.getData().get(group).getWorkscategoryid();
//                if(isHeader){
//                    param.workscategoryid = categoryAdapter.getData().get(group).getWorkscategoryid();
//                }else {
//                    param.workscategoryid = categoryAdapter.getData().get(group).getSublist().get(child).getWorkscategoryid();
//                }
//
                param.workscategoryname = data.getStringExtra("data");

                if(param.workscategoryname.length()>4){
                    ToastUtil.toast(this,"专辑名字不超过四个字");
                    return;
                }
                addSubscription(viewModel.updateCategory(param));

            }
        }




    }
}
